package com.projects.xenia.journals_activities;

import java.util.Calendar;

import com.projects.xenia.GPSLocationActivity;
import com.projects.xenia.R;
import com.projects.xenia.documents_classes.Documents_Visit;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.ref_classes.VisitCausesRefItem;
import com.projects.xenia.ref_classes.VisitCausesRefObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_JournalsTabs  extends TabActivity {
	
	private TabHost tabHost; 
	private Intent journals_orders; 
	
	
	private TextView visit_textview;
	private TextView visit_time;
	private TextView visit_result;	
	private ImageView visit_button;
	
	private Documents_Visit documents_Visit;
	private Context Ctx;
	
	private RelativeLayout VisitLayout;
	
	private Cursor CausesCursor;
	
	private void GetDocVisitByCustomer (String customer_id) {
		
		Cursor VisitsCursor = MainGlobalModule.DBE.rawQuery("select id from xdoc_Visits_H where customers_id = ?", new String [] {customer_id});
		
		if (VisitsCursor.getCount()>0){
			VisitsCursor.moveToFirst();
			documents_Visit = new Documents_Visit();
			documents_Visit.OpenDoc(VisitsCursor.getString(0));
		}
		
	}	
	
	private void GetCausesCursor () {
		
		CausesCursor = MainGlobalModule.DBE.rawQuery("select id as _id, descr from xref_VisitCauses order by descr ", null);		
		
	}
	
	
	
	private void SetVisitStateImage () {
		
		if (documents_Visit!=null) {	
			switch (documents_Visit.Head.visit_state) {
				case 0:
					visit_button.setImageResource(R.drawable.ic_visit_black);
					visit_textview.setText("Начать визит");					
					visit_time.setText(String.format("Время <Пл: %tT>", documents_Visit.Head.date_planned));
					visit_result.setText("");
				break;
				case 1:
					visit_textview.setText("Закончить визит");					
					visit_button.setImageResource(R.drawable.ic_visit_yellow);	
					visit_time.setText(String.format("Время <Пл: %tT>  <Нач.: %tT>", documents_Visit.Head.date_planned, documents_Visit.Head.date_create));
					visit_result.setText("");
				break;
				case 2:
					visit_textview.setText("Визит окончен");					
					visit_button.setImageResource(R.drawable.ic_visit_green);
					visit_time.setText(String.format("Время <Пл: %tT>  <Нач.: %tT>  <Кон.: %tT> ", documents_Visit.Head.date_planned, documents_Visit.Head.date_create,documents_Visit.Head.date_save));
					visit_result.setText("");
				break;
				case 3:
					visit_textview.setText("Визит окончен");
					visit_button.setImageResource(R.drawable.ic_visit_red);
					visit_time.setText(String.format("Время <Пл: %tT>  <Нач.: %tT>  <Кон.: %tT> ", documents_Visit.Head.date_planned, documents_Visit.Head.date_create,documents_Visit.Head.date_save));
					visit_result.setText(documents_Visit.Head.VisitCauses.descr);
				break;
			default:
				break;
			}
			
		}
			
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.journal_tabs);
		
		Ctx = this;
				
		Bundle DocExtra = getIntent().getExtras();		
		String customer_id = DocExtra.getString("customer_id");
		
		tabHost = getTabHost();
		
		GetDocVisitByCustomer (customer_id);
		
		VisitLayout = (RelativeLayout)findViewById(R.id.visit_layout);
		
		if (documents_Visit==null) {
			VisitLayout.setVisibility(View.GONE);
		}
		
		visit_textview = (TextView)findViewById(R.id.visit_textview);
		visit_time = (TextView)findViewById(R.id.visit_time);
		visit_result = (TextView)findViewById(R.id.visit_result);
		
		
		visit_button = (ImageView)findViewById(R.id.visit_button);		
		SetVisitStateImage ();		
				
		visit_button.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {			
				
				switch (documents_Visit.Head.visit_state) {
				
					case 0:
						if (!documents_Visit.CheckOpenVisitsExists ()) {					
							if (documents_Visit.GetLastClosedVisit ()) {							
								Intent GPSLocationActivityIntent = new Intent ();    	
								GPSLocationActivityIntent.setClass(Ctx, GPSLocationActivity.class);		        	
								GPSLocationActivityIntent.putExtra("docid", documents_Visit.Head.id);
								GPSLocationActivityIntent.putExtra("type_xdoc", MainGlobalModule.DocumentsType.Visit);		        	
								startActivityForResult(GPSLocationActivityIntent, 100);						
							}
							else {							
								Toast.makeText(Ctx, "Нельзя начать новый визит, без соблюдения порядка визитов !!!", Toast.LENGTH_SHORT).show();							
							}
						}
						else {
							Toast.makeText(Ctx, "Нельзя начать новый визит, если не закрыт предыдущий !!!", Toast.LENGTH_SHORT).show();
						}
						break;
					case 1:
						if (documents_Visit.CheckOrderExists ()) {
							documents_Visit.Head.date_save = Calendar.getInstance().getTime();							
							documents_Visit.Head.visit_state = 2; // visit is positive close
							documents_Visit.SaveDocToDB();
							SetVisitStateImage ();
						}
						else {							
							GetCausesCursor ();
							if (CausesCursor.getCount()>0) {
								AlertDialog.Builder adb = new Builder (Ctx);
								adb.setTitle("Укажите причину нерезультативного визита");
								adb.setCursor(CausesCursor, new DialogInterface.OnClickListener() {								
									@Override
									public void onClick(DialogInterface dialog, int which) {									
										CausesCursor.moveToPosition(which);
										documents_Visit.Head.VisitCauses = new VisitCausesRefObject(CausesCursor.getString(0)).RefItem;
										documents_Visit.Head.date_save = Calendar.getInstance().getTime();							
										documents_Visit.Head.visit_state = 3; // visit is negative close
										documents_Visit.SaveDocToDB();
										SetVisitStateImage ();
										CausesCursor.close();
										dialog.dismiss();
									}								
								}, "descr");								
								adb.show();	
							}
						}												
				default:
					break;
				}
			}
		});
		
		
		TabHost.TabSpec tabSpec;
	        
		tabSpec = tabHost.newTabSpec("orders");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_orders));
        
        journals_orders = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        journals_orders.setClass(this, Activity_Journal_Orders.class);        
        journals_orders.putExtra("customer_id",customer_id);                
        tabSpec.setContent(journals_orders);
        tabHost.addTab(tabSpec);   
        
        tabSpec = tabHost.newTabSpec("payments");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_payments));
        Intent journals_payments = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        journals_payments.setClass(this, Activity_Journal_Payments.class);        
        journals_payments.putExtra("customer_id",customer_id);
        tabSpec.setContent(journals_payments);
        tabHost.addTab(tabSpec);
        
        tabSpec = tabHost.newTabSpec("returns");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_returns));
        Intent journals_returns = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        
        journals_returns.setClass(this, Activity_Journal_Returns.class);        
        journals_returns.putExtra("customer_id",customer_id);
        tabSpec.setContent(journals_returns);
        tabHost.addTab(tabSpec);
        
        tabSpec = tabHost.newTabSpec("photoreport");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_photos));
        Intent journals_photoreport = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        journals_photoreport.setClass(this, Activity_Journal_PhotoReports.class);        
        journals_photoreport.putExtra("customer_id",customer_id);
        tabSpec.setContent(journals_photoreport);
        tabHost.addTab(tabSpec);
        
        tabSpec = tabHost.newTabSpec("blanks");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_info));
        Intent journals_blanks = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        journals_blanks.setClass(this, Activity_Journal_Blanks.class);        
        journals_blanks.putExtra("customer_id",customer_id);
        tabSpec.setContent(journals_blanks);
        tabHost.addTab(tabSpec);
        
        tabSpec = tabHost.newTabSpec("tasks");
        tabSpec.setIndicator("",getResources().getDrawable(R.drawable.st_tasks));
        Intent journals_tasks = new Intent ().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        journals_tasks.setClass(this, Activity_Journal_Tasks.class);        
        journals_tasks.putExtra("customer_id",customer_id);
        tabSpec.setContent(journals_tasks);
        tabHost.addTab(tabSpec);
        
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		super.onActivityResult(requestCode, resultCode, data);
		
		String tabTag = tabHost.getCurrentTabTag();		
		JournalActivity activity = (JournalActivity)getLocalActivityManager().getActivity(tabTag);
		
		if (requestCode==100) {
			if (resultCode==RESULT_OK) {
				//activity.SetVisibilyty ();
				documents_Visit.Head.date_create = Calendar.getInstance().getTime();
				documents_Visit.Head.date_save = documents_Visit.Head.date_create;
				documents_Visit.Head.visit_state = 1; // visit is open
				documents_Visit.SaveDocToDB();
				SetVisitStateImage ();
			}
			else {
				Toast.makeText(Ctx, "Нельзя начать новый визит, неудалось определить местоположение !!!", Toast.LENGTH_SHORT).show();
			}
		}
		else {					
			activity.onActivityResultFromChild(requestCode, resultCode, data);	
		}		
		
	}
	
	

}
